#ifndef SPEECHWIDGET_H
#define SPEECHWIDGET_H

#include <QWidget>
#include <QPixmap>
#include <QtNetwork/QNetworkRequest>
#include <QtNetwork/QNetworkReply>
#include <QtNetwork/QNetworkSession>
#include <QtNetwork/QNetworkAccessManager>
#include <QtNetwork/QNetworkCookie>
#include <QTextDocument>
#include <QJsonObject>
#include <QJsonDocument>
#include <QJsonArray>
#include <QFile>
#include <QAudioInput>
#include <QAudioOutput>
#include <QAudioFormat>
#include <QAudio>
#include <QBuffer>
#include <QTextToSpeech>
#include <QMap>
#include <QCryptographicHash>
#include <QtEndian>
#include <QSoundEffect>

namespace Ui {
class SpeechWidget;
}

class SpeechWidget : public QWidget
{
    Q_OBJECT

public:
    explicit SpeechWidget(QString resPath,QWidget *parent = nullptr);
    ~SpeechWidget();
public slots:
    void requestFinished(QNetworkReply* reply);
private:
    Ui::SpeechWidget *ui;
    QNetworkAccessManager *manager = new QNetworkAccessManager(this);
    QString token;
    QAudioFormat format;
    QAudioInput *input;
    QAudioOutput *output;

    QBuffer *buff = nullptr;
    QTextToSpeech *tts;
    QFile tmpfile;
    QString resPath;
    QSoundEffect sound;
public:
    static QString GetSubString(QString src, QString pattern);
    static QStringList GetSubStringEX(QString src, QString pattern);
    static QString Unescape(QString src);
    void SendRequest(QString url,QString data="",const QMap<QString,QString> * header = nullptr);
public:
    void STT(QByteArray data);
    void GetToken();
    QString baidu_apikey = "CS2SRdBdZZNZwSntDKmXqOQm";
    QString baidu_seckey = "EF3MqQ7dRSYR5OnxFDV5HEw8Uqukj4zb";
    QString baidu_appid = "15954186";

    const static uint max_wait_time = 2;
    const static uint first_wait_time = 5;
    //const static uint check_value = 70; // it decided by the microphone's value
    uint passtime = 0;
    bool isfirst = true;

    QString aiui_apikey = "e3a144c694c5fdab04411519eecb5246";
    QString aiui_appid = "5c947e7b";
    QString aiui_auth = "8eb691a5e4e5d56e205df8c1f5511dde";
    void AIUI(QString msg);

    void TTS(QString msg);
    static void WriteFile(QString file,QByteArray data);
    static QString MD5(QByteArray data);
public slots:
    void on_pushButton_clicked();
    void on_pushButton_3_clicked();
    void on_pushButton_4_clicked();
    void readData();
    void audioState(QAudio::State state);
    void ttsState(QTextToSpeech::State state);
signals:
    void ChangeState(bool state);
    void ReceiveReply(QJsonObject data);
    void ReceiveSTT(QString data);
    void ButtonState(bool state);
};

#endif // WIDGET_H
